<template>
  <div class="travel-daily">
    <v-calendar ref="calendarRef" :attributes='dailyInfo.attrs'
               @dayclick="dateClick" @did-move="changeMonthClick"
                :is-dark="appStore.isDark"
                class="travel-calendar card-item"/>

    <travel-daily-item :date="dailyInfo.calendarDate"/>
  </div>
</template>

<script setup lang="ts">
import TravelDailyItem from '@/components/Travel/TravelDailyItem.vue'
import { reactive, watch, ref, onMounted } from 'vue'
import { useTravelStore } from '@/store/travel.ts'
import { formatDate } from 'vue3-common/utils/dateUtil'
import { CalendarDay } from 'v-calendar/dist/types/src/utils/page'
import { useAppStore } from '@/store/app.ts'

const calendarRef = ref()
const travelStore = useTravelStore()
const appStore = useAppStore()

onMounted(() => {
  const { month } = travelStore.queryRecord
  calendarRef.value.move(new Date(month))
})

watch(() => travelStore.isRefresh, () => {
  updateInfo()
})

const dailyInfo = reactive({
  calendarDate: '',
  attrs: [] as any[]
})

const updateInfo = () => {
  getCalendarMoveDate()
  getCalendarAttrDates()
}

const getCalendarMoveDate = () => {
  const recordLength = travelStore.travelRecordList.length
  if (recordLength > 0) {
    const today = formatDate(new Date())
    if (travelStore.travelRecordList.some((item) => item.date === today)) {
      dailyInfo.calendarDate = today
    } else {
      dailyInfo.calendarDate = formatDate(travelStore.travelRecordList[recordLength - 1].date)
    }
  } else {
    dailyInfo.calendarDate = ''
  }
}

const getCalendarAttrDates = () => {
  dailyInfo.attrs = []
  dailyInfo.attrs.push({
    key: 'today',
    highlight: true,
    dates: new Date()
  })

  const dateList = travelStore.travelRecordList.map((item) => item.date)
  dailyInfo.attrs.push({
    dot: 'red',
    dates: [...new Set(dateList)]
  })
}

/**
 * 选择日期事件
 * @param day 日期
 */
const dateClick = (day: CalendarDay) => {
  dailyInfo.calendarDate = formatDate(day.date)
}

/**
 * 选择月份事件
 */
const changeMonthClick = async (value) => {
  travelStore.queryRecord.month = value[0].id
  await travelStore.refreshInfo()
}
</script>

<style lang="scss">
.travel-daily {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 1vh;

  .travel-calendar {
    width: 100%;
    justify-self: center;
    align-self: center;
  }
}
</style>
